/**************************************************************************************
 *
 * @(#) ExcelImageExtractor.java
 * @Package com.jgdt.jgdtkasannong_university_gene_backend.utils
 **************************************************************************************/
package com.jgdt.jgdtkasannong_university_gene_backend.utils.excel;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ooxml.POIXMLDocumentPart;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;

import java.util.*;
/**
 * @description: 构建表格图片锚点，构建指定shell图片数据
 * @author: huangAn
 * @createDate: 2025/04/29
 */
public class ExcelImageExtractor {

    public static Map<Integer, Map<Integer, PictureData>> buildImageAnchorMap(Sheet sheet) {
        Map<Integer, Map<Integer, PictureData>> imageAnchorMap = new HashMap<>();

        // 处理 XSSF (.xlsx) 格式
        if (sheet instanceof XSSFSheet) {
            XSSFSheet xssfSheet = (XSSFSheet) sheet;
            for (POIXMLDocumentPart part : xssfSheet.getRelations()) {
                if (part instanceof XSSFDrawing) {
                    XSSFDrawing drawing = (XSSFDrawing) part;
                    List<XSSFShape> shapes = drawing.getShapes();
                    for (XSSFShape shape : shapes) {
                        if (shape instanceof XSSFPicture) {
                            XSSFPicture picture = (XSSFPicture) shape;
                            XSSFClientAnchor anchor = picture.getPreferredSize();
                            int row = anchor.getRow1();
                            int col = anchor.getCol1();
                            imageAnchorMap
                                    .computeIfAbsent(row, k -> new HashMap<>())
                                    .put(col, picture.getPictureData());
                        }
                    }
                }
            }
        }
        // 处理 HSSF (.xls) 格式
        else if (sheet instanceof HSSFSheet) {
            HSSFSheet hssfSheet = (HSSFSheet) sheet;
            HSSFPatriarch patriarch = hssfSheet.getDrawingPatriarch();
            if (patriarch != null) {
                for (HSSFShape shape : patriarch.getChildren()) {
                    if (shape instanceof HSSFPicture) {
                        HSSFPicture picture = (HSSFPicture) shape;
                        HSSFClientAnchor anchor = (HSSFClientAnchor) picture.getAnchor();
                        int row = anchor.getRow1();
                        int col = anchor.getCol1();
                        imageAnchorMap
                                .computeIfAbsent(row, k -> new HashMap<>())
                                .put(col, picture.getPictureData());
                    }
                }
            }
        }
        return imageAnchorMap;
    }
}




